package com.matrix.im.application;

import com.matrix.api.im.vo.ChatMessageVO;
import com.matrix.common.constant.RedisConstants;
import com.matrix.im.converter.ImConverter;
import com.matrix.im.domain.model.ChatMessage;
import com.matrix.im.infrastructure.persistence.repository.ChatMessageMongoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Service
@RequiredArgsConstructor
public class MessagePullService {

    private final StringRedisTemplate redisTemplate;
    private final ChatMessageMongoRepository chatMessageMongoRepository;

    public List<ChatMessageVO> pullNewMessages(Long userId, long lastMsgSeq) {
        String inboxKey = RedisConstants.buildKey(RedisConstants.IM_INBOX_KEY_PREFIX, userId);

        Set<String> messageIds = redisTemplate.opsForZSet().rangeByScore(inboxKey, lastMsgSeq + 1, Double.MAX_VALUE);

        if (CollectionUtils.isEmpty(messageIds)) {
            return Collections.emptyList();
        }

        List<ChatMessage> messages = chatMessageMongoRepository.findAllById(messageIds);

        redisTemplate.opsForZSet().remove(inboxKey, messageIds);

        return messages.stream()
                .sorted(java.util.Comparator.comparing(ChatMessage::getTimestamp))
                .map(ImConverter.INSTANCE::toChatMessageVO)
                .collect(Collectors.toList());
    }
}
